package org.fb.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.fb.dto.RpcRequest;
import org.fb.dto.RpcResponse;
import org.fb.service.UserServiceImpl;

import java.lang.reflect.Method;

/**
 * @author fanbo@imoran.net
 * @date 2021/2/6 18:03
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    /**
     * 当客户端读取数据时,该方法会被调用
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //注意:  客户端将来发送请求的时候会传递一个参数:  UserService#sayHello#...
        RpcRequest rpcRequest = (RpcRequest) msg;
        System.out.println("服务端接收：" + rpcRequest.getRequestId());
        //通过反射获取class
        Class<?> aClass = Class.forName(rpcRequest.getClassName());
        //借助实现ApplicationContextAware接口获取Bean
        Object bean = SpringJobBeanFactory.getBean(aClass);
        //获取方法
        Method declaredMethod = aClass.getDeclaredMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        //invoke调用方法
        RpcResponse rpcResponse = (RpcResponse) declaredMethod.invoke(bean, rpcRequest.getParameters());

        //把调用实现类的方法获得的结果写到客户端
        rpcResponse.setResponseId(rpcRequest.getRequestId());
        ctx.writeAndFlush(rpcResponse);
    }
}
